<template>
  <u-upload
      :file-list="fileList"
      previewFullImage
      :max-count="compMaxCount"
      :disabled="props.type !== 'upload'"
      @afterRead="handlerOldImgAfterRead"
      @delete="handlerOldImgDelete"
  />
</template>

<script lang="ts" setup>
import UUpload from "@/uni_modules/uview-plus/components/u-upload/u-upload.vue";
import {computed, ref, watch} from "vue";
import {getFileUploadToken} from "@/api/resource";

const props = withDefaults(defineProps<{
  type: 'upload' | 'read',
  modelValue: string[],
  maxCount: number
}>(),{
  type: 'upload',
  modelValue(){
    return []
  },
  maxCount: 10
})
const emits = defineEmits(['update:modelValue','uploadAfter','delete'])

const compMaxCount = computed(() => {
  return props.type === 'read' ? fileList.value.length : props.maxCount
})

const fileList = ref<QFile[]>([])
const fnUploadFilePromise = async (url: string) => {
  const { data } = await getFileUploadToken()
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://up-z2.qiniup.com',
      filePath: url,
      name: 'file',
      formData:{
        token: data
      },
      success: (res) => {
        const data = JSON.parse(res.data)
        resolve(data.key)
      },
      complete: (error) => {
        reject(error)
      }
    })
  })
}
interface QFile {
  url: string
  status: string
  message: string
}
// 旧图片上传前的
const handlerOldImgAfterRead = async (event:any) => {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file)
  let fileListLen = fileList.value.length
  lists.map((item) => {
    fileList.value.push({
      url: item.url,
      status: 'uploading',
      message: '上传中'
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await fnUploadFilePromise(lists[i].url)
    let item = fileList.value[fileListLen]
    fileList.value.splice(fileListLen, 1, Object.assign(item, {
      status: 'success',
      message: '',
      url: 'http://bstore.longapp.top/' + result
    }))
    fileListLen++
  }
  emits('update:modelValue', fileList.value.map(item => item.url))
  emits('uploadAfter',event)
}
// 图片删除事件
const handlerOldImgDelete = (event:any) => {
  fileList.value.splice(event.index, 1)
  emits('update:modelValue', fileList.value.map(item => item.url))
  emits('delete',event)
}

watch(() => props.modelValue,(newVal,oldVal) => {
  if(newVal !== oldVal){
    fileList.value = newVal.map(item => {
      return {
        status: 'success',
        message: '',
        url: item
      }
    })
  }
})
</script>

<style scoped lang="scss">
</style>